package com.yu1996.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.yu1996.common.to.es.SkuEsModel;
import com.yu1996.gulimall.search.config.GulimallElasticSearchConfig;
import com.yu1996.gulimall.search.constant.EsConstant;
import com.yu1996.gulimall.search.service.ProductSaveService;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ProductSaveServiceImpl implements ProductSaveService {

  @Autowired private RestHighLevelClient restHighLevelClient;

  /**
   * 将数据保存到ES
   * 用bulk代替index，进行批量保存
   * BulkRequest bulkRequest, RequestOptions options
   */
  @Override
  public boolean productSaveService(List<SkuEsModel> models) throws IOException {
    // 批量保存商品sku信息
    BulkRequest bulkRequest = new BulkRequest();
    for (SkuEsModel model : models) {
      IndexRequest index = new IndexRequest(EsConstant.PRODUCT_INDEX);
      index.id(model.getSkuId().toString());
      String json = JSON.toJSONString(model);
      index.source(json, XContentType.JSON);
      bulkRequest.add(index);
    }
    BulkResponse bulk =
        restHighLevelClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
    boolean hasFailures = bulk.hasFailures();
    //TODO 如果批量错误
//    Arrays.stream(bulk.getItems()).map(item->{
//
//    })
    return !hasFailures;
  }
}
